package com.chen.utils;

import cn.hutool.core.util.URLUtil;
import com.chen.pojo.bean.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


@Component
@SuppressWarnings("all")
public class HtmlParseUtil {
    public static void main(String[] args) throws IOException {
        new HtmlParseUtil().pareseJD("java").forEach(System.out::println);
    }

    public List<Content> pareseJD(String keywords) throws IOException {
        ArrayList<Content> goodsList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            String url = "https://search.jd.com/Search?keyword=" + URLUtil.encode(keywords,"UTF-8") + "&page=" + i;
            //解析网页
            Document document = Jsoup.parse(new URL(url), 3000);  //就是返回的js页面对象
            Element element = document.getElementById("J_goodsList");
            //获取所有的li元素  标签
            Elements elements = element.getElementsByTag("li");

            //获取元素中的内容 el就是每一个li标签  attr获取属性  eq(0)获取第一个  text文档
            for (Element el : elements) {
                String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
                System.out.println("https:" + img);
                String price = el.getElementsByClass("p-price").eq(0).text();
                System.out.println(price);
                String title = el.getElementsByClass("p-name").eq(0).text();
                System.out.println(title);
                Content content = new Content();
                content.setTitle(title);
                content.setImg("https://" + img);
                content.setPrice(price);
                goodsList.add(content);
            }
            return goodsList;
        }

        return goodsList;
    }

}
